package com.googlecode.c4e.ui.wizards;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWizard;
import org.eclipse.ui.PlatformUI;

import com.googlecode.c4e.api.Registry;
import com.googlecode.c4e.api.model.Server;
import com.googlecode.c4e.ui.views.ServersView;

public class AddServerWizard extends Wizard implements INewWizard {

	private AddServerWizardPage page;
	private ISelection selection;

	/**
	 * Constructor for AddServerWizard.
	 */
	public AddServerWizard() {
		super();
	}

	/**
	 * Adding the page to the wizard.
	 */

	public void addPages() {
		page = new AddServerWizardPage(selection);
		addPage(page);
	}

	/**
	 * This method is called when 'Finish' button is pressed in the wizard. We
	 * will create an operation and run it using wizard as execution context.
	 */
	public boolean performFinish() {
		Server server = new Server();
		server.setUrl(page.getUrl());
		server.setLabel(page.getLabel());
		server.setUsername(page.getUsername());
		server.setPassword(page.getPassword());
		boolean isOk = false;
		try {
			Registry.getDefault().verifyServer(server);
			isOk = true;
		} catch (Exception e) {
			Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
					.getShell();
			isOk = MessageDialog.openQuestion(shell, "Error during validation",
					"Error occured during connecting to server: "
							+ e.getMessage() + " Keep location anyway?");
		}
		if (isOk) {
			Registry.getDefault().saveServer(server);
			// TODO find an official way of doing this
			ServersView serversView = (ServersView) PlatformUI.getWorkbench()
					.getActiveWorkbenchWindow().getActivePage().findView(
							"com.googlecode.c4e.ui.views.ServersView");
			if (serversView != null) {
				serversView.refreshViewer();
			}
		}
		return isOk;
	}

	/**
	 * We will accept the selection in the workbench to see if we can initialize
	 * from it.
	 * 
	 * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
	 */
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		this.selection = selection;
	}
}